package com.mall.shopping.services;

import com.mall.shopping.ICartService;
import com.mall.shopping.constants.ShoppingRetCode;
import com.mall.shopping.converter.CartConverter;
import com.mall.shopping.dal.entitys.Item;
import com.mall.shopping.dal.persistence.ItemMapper;
import com.mall.shopping.dto.*;
import com.mall.shopping.utils.ExceptionProcessorUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Service;
import org.redisson.api.RMap;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.Date;

/**
 * @Author: itsxslyn
 * @Date: 2021/9/28 23:33
 * @Description:
 */

@Slf4j
@Service
public class ICartServiceImpl implements ICartService {

    private final String CART = "cart";

    @Autowired
    RedissonClient redissonClient;

    @Autowired
    ItemMapper itemMapper;

    @Autowired
    CartConverter cartConverter;

    @Override
    public CartListByIdResponse getCartListById(CartListByIdRequest request) {

        CartListByIdResponse response = new CartListByIdResponse();
        try {
            request.requestCheck();
            ArrayList<CartProductDto> cartVos = new ArrayList<>();
            RMap<Object, CartProductDto> map = redissonClient.getMap(request.getUserId() + CART);
            map.forEach((k, v) -> cartVos.add(v));
            cartVos.sort((o1, o2) -> -o1.getUpdateTime().compareTo(o2.getUpdateTime()));
            //cartVos.sort(Comparator.comparing(CartProductDto::getUpdateTime));
            response.setCartProductDtos(cartVos);
            response.setCode(ShoppingRetCode.SUCCESS.getCode());
            response.setMsg(ShoppingRetCode.SUCCESS.getMessage());
        } catch (Exception e) {
            log.error("IcartServiceImpl.getCartListById occur Exception :" + e);
            ExceptionProcessorUtils.wrapperHandlerException(response, e);
        }

        return response;
    }

    @Override
    public AddCartResponse addToCart(AddCartRequest request) {
        AddCartResponse response = new AddCartResponse();

        try {
            request.requestCheck();
            RMap<Object, Object> rMap = redissonClient.getMap(request.getUserId() + CART);
            //先判断该商品在不在购物车
            if (rMap.containsKey(request.getItemId())) {
                CartProductDto cartVo = (CartProductDto) rMap.get(request.getItemId());
                cartVo.setProductNum(cartVo.getProductNum() + request.getNum());
                cartVo.setUpdateTime(new Date());
                rMap.put(request.getItemId(), cartVo);
            } else {
                //查数据库
                Item item = itemMapper.selectByPrimaryKey(request.getItemId());
                CartProductDto cartVo = cartConverter.item2CartVo(item);
                cartVo.setChecked("true");
                cartVo.setProductNum(request.getNum());
                String[] split = item.getImage().split(",");
                cartVo.setProductImg(split[0]);
                cartVo.setUpdateTime(new Date());
                rMap.put(cartVo.getProductId(), cartVo);
            }
            response.setCode(ShoppingRetCode.SUCCESS.getCode());
            response.setMsg(ShoppingRetCode.SUCCESS.getMessage());
        } catch (Exception e) {
            log.error("IcartServiceImpl.addToCart occur Exception :" + e);
            ExceptionProcessorUtils.wrapperHandlerException(response, e);
        }

        return response;
    }

    @Override
    public UpdateCartNumResponse updateCartNum(UpdateCartNumRequest request) {
        UpdateCartNumResponse response = new UpdateCartNumResponse();
        try {
            request.requestCheck();
            RMap<Object, CartProductDto> map = redissonClient.getMap(request.getUserId() + CART);
            CartProductDto cartProductDto = map.get(request.getItemId());
            cartProductDto.setProductNum(request.getNum());
            cartProductDto.setChecked(request.getChecked());
            map.put(request.getItemId(), cartProductDto);
            response.setCode(ShoppingRetCode.SUCCESS.getCode());
            response.setMsg(ShoppingRetCode.SUCCESS.getMessage());
        } catch (Exception e) {
            log.error("ICartServiceImpl.updateCartNum occur Exception :" + e);
            ExceptionProcessorUtils.wrapperHandlerException(response, e);
        }

        return response;
    }

    @Override
    public CheckAllItemResponse checkAllCartItem(CheckAllItemRequest request) {
        CheckAllItemResponse response = new CheckAllItemResponse();

        try {
            request.requestCheck();
            RMap<Object, CartProductDto> map = redissonClient.getMap(request.getUserId() + CART);
            map.forEach((k, v) -> {
                v.setChecked(request.getChecked());
                map.put(k, v);
            });
            response.setCode(ShoppingRetCode.SUCCESS.getCode());
            response.setMsg(ShoppingRetCode.SUCCESS.getMessage());
        } catch (Exception e) {
            log.error("IcartServiceImpl.checkAllCartItem occur Exception :" + e);
            ExceptionProcessorUtils.wrapperHandlerException(response, e);
        }
        return response;
    }


    @Override
    public DeleteCartItemResponse deleteCartItem(DeleteCartItemRequest request) {
        DeleteCartItemResponse response = new DeleteCartItemResponse();
        try {
            request.requestCheck();
            RMap<Object, CartProductDto> map = redissonClient.getMap(request.getUserId() + CART);
            map.remove(request.getItemId());
            response.setCode(ShoppingRetCode.SUCCESS.getCode());
            response.setMsg(ShoppingRetCode.SUCCESS.getMessage());
        } catch (Exception e) {
            log.error("IcartServiceImpl.addToCart occur Exception :" + e);
            ExceptionProcessorUtils.wrapperHandlerException(response, e);
        }
        return response;
    }

    @Override
    public DeleteCheckedItemResponse deleteCheckedItem(DeleteCheckedItemRequest request) {
        DeleteCheckedItemResponse response = new DeleteCheckedItemResponse();
        try {
            request.requestCheck();
            RMap<Object, CartProductDto> map = redissonClient.getMap(request.getUserId() + CART);
            map.forEach((k, v) -> {
                if (Boolean.parseBoolean(v.getChecked())) {
                    map.remove(k);
                }
            });
            response.setCode(ShoppingRetCode.SUCCESS.getCode());
            response.setMsg(ShoppingRetCode.SUCCESS.getMessage());
        } catch (Exception e) {
            log.error("IcartServiceImpl.addToCart occur Exception :" + e);
            ExceptionProcessorUtils.wrapperHandlerException(response, e);
        }
        return response;
    }

    @Override
    public ClearCartItemResponse clearCartItemByUserID(ClearCartItemRequest request) {
        return null;
    }
}
